package com.droidwatcher.activity;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.droidwatcher.JsonEntity.HttpRequestHead;
import com.droidwatcher.JsonEntity.RegAndLoginJsonObj;
import com.droidwatcher.JsonEntity.RegistAndLoginEntityInfo;
import com.droidwatcher.JsonEntity.RegistAndLoginResponse;
import com.droidwatcher.MyApplication;
import com.droidwatcher.SettingsManager;
import com.droidwatcher.retrofit.MyRetrofitFactory;
import com.droidwatcher.util.AXLog;
import com.droidwatcher2.R;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link LoginFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LoginFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LoginFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    TextView tv_reg  , tv_forget;
    private OnFragmentInteractionListener mListener;

    LoginCallback callback ;
    private SettingsManager settings;
    EditText CET_username,CET_password;
    Button btn_login;
    public LoginFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LoginFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settings = new SettingsManager(getActivity());
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        AXLog.e("wzytest","run on fragment onCreateView");
        View view =  inflater.inflate(R.layout.fragment_login, container, false);
        initView(view);
        return view ;
    }

    private void initView(View view) {
        tv_reg  = (TextView) view.findViewById(R.id.tv_reg);
        tv_reg.setOnClickListener(this);
        tv_forget = (TextView) view.findViewById(R.id.tv_forgetpwd);
        tv_forget.setOnClickListener(this);
        CET_username = (EditText) view.findViewById(R.id.CET_username);
        CET_password = (EditText) view.findViewById(R.id.CET_password);
        btn_login = (Button) view.findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        callback = (LoginCallback) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_reg:
                callback.toRegister();
                break;
            case R.id.tv_forgetpwd:
                callback.toFindpwd();
                break;
            case R.id.btn_login:
                login();
                break;
        }
    }

    private void login() {
        if(TextUtils.isEmpty(CET_username.getText().toString())){
            Toast.makeText( getActivity(),getResources().getString(R.string.please_input_email),Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(CET_password.getText().toString())){
            Toast.makeText( getActivity(),getResources().getString(R.string.please_input_pwd),Toast.LENGTH_SHORT).show();
            return;
        }

        RegAndLoginJsonObj obj = new RegAndLoginJsonObj();
        obj.setHead(new HttpRequestHead());
        RegistAndLoginEntityInfo info  = new RegistAndLoginEntityInfo();
        info.setPassword(CET_password.getText().toString());
        info.setUsername(CET_username.getText().toString());
        obj.setInfo(info);
        RequestBody body = RequestBody.create(MediaType.parse("text/plain"), JSON.toJSONString(obj));

        AXLog.e("wzytest","JSON.toJSONString(obj):"+JSON.toJSONString(obj));
        MyRetrofitFactory.getSendAPISingleton().login(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RegistAndLoginResponse>() {

                   @Override
                   public void onCompleted() {
                        AXLog.e("wzytest","run in onCompleted");
                   }

                   @Override
                   public void onError(Throwable e) {

                       AXLog.e("wzytest","run in onError");
                       e.printStackTrace();
                       Toast.makeText(getActivity(), R.string.loginFailed, Toast.LENGTH_LONG).show();
                   }

                   @Override
                   public void onNext(RegistAndLoginResponse loginResponse) {
                       AXLog.e("wzytest","run in onNext:"+loginResponse);
                       if (loginResponse.getMeta().getCode() == 0) {
                           try {
                               settings.getSettings().edit().putString("LOGIN", CET_username.getText().toString()).commit();
                               settings.getSettings().edit().putLong("uid", loginResponse.getData().getUid()).commit();
                               settings.getSettings().edit().putString("token", loginResponse.getData().getToken()).commit();
                               startActivity(new Intent(getActivity(), MainMenuActivity.class));
                               getActivity().finish();
                           }catch (Exception e){
                               Toast.makeText(MyApplication.app,R.string.loginFailed,Toast.LENGTH_SHORT).show();
                           }
                       } else if(loginResponse.getMeta().getCode() == 1){
                           Toast.makeText(MyApplication.app,R.string.loginFailed,Toast.LENGTH_SHORT).show();
                       }else{
                           Toast.makeText(MyApplication.app,R.string.loginFailed1,Toast.LENGTH_SHORT).show();
                       }
                   }
               });
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
